﻿<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
  
  <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-39155502-5"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
  
      gtag('config', 'UA-39155502-5');
    </script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Find queries | MongoDB.Entities </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Find queries | MongoDB.Entities ">
    <meta name="generator" content="docfx 2.58.0.0">
    <meta name="description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management.">
    <link rel="shortcut icon" href="../images/favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    
    <meta property="docfx:rel" content="../">
    <meta property="docfx:newtab" content="true">
    <meta property="og:title" content="MongoDB.Entities">
    <meta property="og:site_name" content="MongoDB.Entities">
    <meta property="og:url" content="https://mongodb-entities.com">
    <meta property="og:description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management,">
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://mongodb-entities.com/images/social-square.png">  
  </head>
  <body data-spy="scroll" data-target="#affix" data-offset="120">
    <div id="wrapper">
      <header>
        
        <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              
              <a class="navbar-brand" href="../index.html">
                <img id="logo" class="svg" src="../images/icon.png" alt="">
              </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar">
              <form class="navbar-form navbar-right" role="search" id="search">
                <div class="form-group">
                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
                </div>
              </form>
            </div>
          </div>
        </nav>
        
        <div class="subnav navbar navbar-default">
          <div class="container hide-when-search" id="breadcrumb">
            <ul class="breadcrumb">
              <li></li>
            </ul>
          </div>
        </div>
      </header>
      <div class="container body-content">
        
        <div id="search-results">
          <div class="search-list">Search Results for <span></span></div>
          <div class="sr-items">
            <p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
          </div>
          <ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
        </div>
      </div>
      <div role="main" class="container body-content hide-when-search">
        
        <div class="sidenav hide-when-search">
          <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
          <div class="sidetoggle collapse" id="sidetoggle">
            <div id="sidetoc"></div>
          </div>
        </div>
        <div class="article row grid-right">
          <div class="col-md-10">
            <article class="content wrap" id="_content" data-uid="">
<h1 id="find-queries">Find queries</h1>

<p>several overloads are available for finding entities as shown below.</p>
<h3 id="find-one-by-id">Find one by ID</h3>
<pre><code class="lang-csharp">var author = await DB.Find&lt;Author&gt;().OneAsync(&quot;ID&quot;);
</code></pre>
<h3 id="find-many-by-lambda">Find many by lambda</h3>
<pre><code class="lang-csharp">var authors = await DB.Find&lt;Author&gt;().ManyAsync(a =&gt; a.Publisher == &quot;Harper Collins&quot;);
</code></pre>
<h3 id="find-many-by-filter">Find many by filter</h3>
<pre><code class="lang-csharp">var authors = await DB.Find&lt;Author&gt;()
                      .ManyAsync(f=&gt; f.Eq(a=&gt;a.Surname,&quot;Stark&quot;) &amp; f.Gt(a=&gt;a.Age,35));
</code></pre>
<div class="TIP">
<h5>Tip</h5>
<p>all the <a href="https://mongodb.github.io/mongo-csharp-driver/2.11/apidocs/html/Methods_T_MongoDB_Driver_FilterDefinitionBuilder_1.htm"><em>filter definition builder</em></a> methods of the official driver are available for use as shown above.</p>
</div>
<h3 id="find-by-2d-coordinates">Find by 2D coordinates</h3>
<pre><code class="lang-csharp">var cafes = await DB.Find&lt;Cafe&gt;()
                    .Match(c =&gt; c.Location, new Coordinates2D(48.857908, 2.295243), 1000)
                    .ExecuteAsync()
</code></pre>
<blockquote>
<p>see <a href="https://dev.to/djnitehawk/tutorial-geospatial-search-in-mongodb-the-easy-way-kbd"><em>this tutorial</em></a> for a detailed walkthrough.</p>
</blockquote>
<h2 id="find-by-aggregation-expression-expr">Find by aggregation expression ($expr)</h2>
<pre><code class="lang-csharp">var authors = await DB.Find&lt;Author&gt;()
                      .MatchExpression(&quot;{$gt:['$TotalSales','$SalesGoal']}&quot;)
                      .ExecuteAsync();
</code></pre>
<div class="TIP">
<h5>Tip</h5>
<p>aggregation <a href="https://docs.mongodb.com/manual/reference/operator/query/expr/"><em>expressions</em></a> lets you refer to properties of the same entity using the $ notation as well as enable you to use aggregation framework operators in find queries.</p>
</div>
<h1 id="advanced-find">Advanced find</h1>
<h2 id="sorting-paging-and-projecting">Sorting, paging and projecting</h2>
<pre><code class="lang-csharp">var authors = await DB.Find&lt;Author&gt;()
                      .Match(a =&gt; a.Age &gt; 30)
                      .Sort(a =&gt; a.Age, Order.Descending)
                      .Sort(a =&gt; a.Name, Order.Ascending)
                      .Skip(1).Limit(1)
                      .Project(a =&gt; new Author { Name = a.Name })
                      .ExecuteAsync();
</code></pre>
<p>the search criteria is specified using <code>.Match()</code> which takes either an <strong>ID</strong>, <strong>lambda expression</strong>, <strong>filter expression</strong>, <strong>geospatial</strong>, or <strong>full/fuzzy text search query</strong>.</p>
<p>sorting is specified using <code>.Sort()</code> which takes in a lambda for the property to sort by and in which order. <code>.Sort()</code> can be used multiple times in order to specify multiple sorting stages. when doing text queries, you can sort the results by mongodb's 'meta text score' by using the <code>.SortByTextScore()</code> method.</p>
<p>how many items to skip and take are specified using <code>.Skip()</code> and <code>.Limit()</code></p>
<h3 id="projections">Projections</h3>
<p>to avoid the complete entity being returned, you can use <code>.Project()</code> with a lambda expression to get back only the properties you need as shown above. it is also possible to use projection builder methods like so:</p>
<pre><code class="lang-csharp">.Project(p =&gt; p.Include(&quot;Name&quot;).Exclude(&quot;Surname&quot;))
</code></pre>
<div class="TIP">
<h5>Tip</h5>
<p>to be able to chain projection builder methods like above, please add the import statement <strong>using MongoDB.Driver;</strong> to your class.</p>
</div>
<h4 id="projection-with-exclusions">Projection with exclusions</h4>
<p>it is also possible to specify an exclusion projection with a <code>new</code> expression like so:</p>
<pre><code class="lang-csharp">var res = await DB.Find&lt;Author&gt;()
                  .Match(a =&gt; a.ID == &quot;xxxxxxxxxxx&quot;)
                  .ProjectExcluding(a =&gt; new { a.Age, a.Name })
                  .ExecuteSingleAsync();
</code></pre>
<p>doing so will return an Author entity with all the properties populated except for the Age and Name properties.</p>
<h4 id="project-to-a-different-type">Project to a different type</h4>
<p>in order to project to a different result type than the input entity type, simply use the generic overload like so:</p>
<pre><code class="lang-csharp">var name = await DB.Find&lt;Author,string&gt;()
                   .Match(a =&gt; a.ID == &quot;xxxxxxxxxxx&quot;)
                   .Project(a =&gt; a.FirstName + &quot; &quot; + a.LastName)
                   .ExecuteSingleAsync();
</code></pre>
<h2 id="execute">Execute</h2>
<p>no command is sent over the wire to mongodb until you call one of the following <code>Execute*()</code> methods:</p>
<p><strong>ExecuteCursorAsync():</strong> gets a cursor you can iterate over instead of a list of entities.</p>
<p><strong>ExecuteAsync():</strong> gets a list of matched entities or default value if nothing matched.</p>
<p><strong>ExecuteSingleAsync():</strong> gets only 1 matched entity and will throw an exception if more than 1 entity is matched, or default value if nothing matched.</p>
<p><strong>ExecuteFirstAsync():</strong> gets the first of the matched entities, or default value if nothing matched.</p>
<p><strong>ExecuteAnyAsync():</strong> gets a boolean indicating whether there were any matches.</p>
</article>
          </div>
          
          <div class="hidden-sm col-md-2" role="complementary">
            <div class="sideaffix">
              <div class="contribution">
                <ul class="nav">
                </ul>
              </div>
              <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
                <h5>In This Article</h5>
                <div></div>
              </nav>
            </div>
          </div>
        </div>
      </div>
      
      <footer>
        <div class="grad-bottom"></div>
        <div class="footer">
          <div class="container">
            <span class="pull-right">
              <a href="#top">Back to top</a>
            </span>
            Developed by <a href='https://github.com/dj-nitehawk'>Đĵ ΝιΓΞΗΛψΚ</a> and <a href='https://github.com/dj-nitehawk/MongoDB.Entities/graphs/contributors'>contributors</a> / Licensed under <a href='https://github.com/dj-nitehawk/MongoDB.Entities/blob/master/LICENSE'>MIT</a> / Website generated by <a href='https://dotnet.github.io/docfx/'>DocFX</a>
            
          </div>
        </div>
      </footer>
    </div>
    
    <script type="text/javascript" src="../styles/docfx.vendor.js"></script>
    <script type="text/javascript" src="../styles/docfx.js"></script>
    <script type="text/javascript" src="../styles/main.js"></script>
  </body>
</html>
